package com.coalmine.activiti.webadmin.upms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.coalmine.activiti.webadmin.upms.dao.ActDeBusinessMapper;
import com.coalmine.activiti.webadmin.upms.dao.ActDeptMapper;
import com.coalmine.activiti.webadmin.upms.model.ActDeBusiness;
import com.coalmine.activiti.webadmin.upms.model.ActDept;
import com.coalmine.activiti.webadmin.upms.service.IActDeBusinessService;
import com.coalmine.common.core.exception.CustomException;
import com.coalmine.common.core.utils.IdUtils;
import com.coalmine.common.core.utils.SecurityUtils;
import com.coalmine.common.core.utils.StringUtils;
import org.springframework.util.CollectionUtils;

/**
 * 业务类型Service业务层处理
 *
 * @author coalmine
 * @date 2021-08-21
 */
@Service
public class ActDeBusinessServiceImpl implements IActDeBusinessService
{
    private static final Logger log = LoggerFactory.getLogger(ActDeBusinessServiceImpl.class);
    @Autowired
    private ActDeBusinessMapper actDeBusinessMapper;
    
    @Autowired
    private ActDeptMapper actDeptMapper;

    /**
     * 查询业务类型
     *
     * @param id 业务类型主键
     * @return 业务类型
     */
    @Override
    public ActDeBusiness selectActDeBusinessById(String id)
    {
        return actDeBusinessMapper.selectActDeBusinessById(id);
    }

    /**
     * 查询业务类型列表
     *
     * @param actDeBusiness 业务类型
     * @return 业务类型
     */
    @Override
    public List<ActDeBusiness> selectActDeBusinessList(ActDeBusiness actDeBusiness)
    {
        return actDeBusinessMapper.selectActDeBusinessList(actDeBusiness);
    }

    /**
     * 新增业务类型
     *
     * @param actDeBusiness 业务类型
     * @return 结果
     */
    @Override
    @Transactional
    public int insertActDeBusiness(ActDeBusiness actDeBusiness)
    {
        actDeBusiness.setId(IdUtils.simpleUUID());
        actDeBusiness.setCreateTime(new Date());
        actDeBusiness.setCreateBy(SecurityUtils.getUsername());
        actDeBusiness.setUpdateBy(SecurityUtils.getUsername());
        insertActDept(actDeBusiness);
        return actDeBusinessMapper.insertActDeBusiness(actDeBusiness);
    }

    /**
     * 修改业务类型
     *
     * @param actDeBusiness 业务类型
     * @return 结果
     */
    @Override
    @Transactional
    public int updateActDeBusiness(ActDeBusiness actDeBusiness)
    {
        actDeBusiness.setCreateBy(SecurityUtils.getUsername());
        actDeBusiness.setUpdateBy(SecurityUtils.getUsername());
        actDeBusiness.setUpdateTime(new Date());
        actDeptMapper.deleteActByActId(actDeBusiness.getId());
        insertActDept(actDeBusiness);
        return actDeBusinessMapper.updateActDeBusiness(actDeBusiness);
    }

    /**
     * 批量删除业务类型
     *
     * @param ids 需要删除的业务类型主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteActDeBusinessByIds(String[] ids)
    {
    	for (String id : ids) {
    		actDeptMapper.deleteActByActId(id);
		}
        return actDeBusinessMapper.deleteActDeBusinessByIds(ids);
    }

    /**
     * 删除业务类型信息
     *
     * @param id 业务类型主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteActDeBusinessById(String id)
    {
    	actDeptMapper.deleteActByActId(id);
        return actDeBusinessMapper.deleteActDeBusinessById(id);
    }

    /**
     * 根据表明查询信息
     *
     * @param tableName 业务表名
     * @return 结果
     */
    @Override
    public Integer findByDefIdAndTableName(String tableName){
        return actDeBusinessMapper.findByDefIdAndTableName(tableName);
    }

    /**
     * 导入业务类型数据
     *
     * @param businessList 业务类型列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importActDeBusiness(List<ActDeBusiness> businessList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(businessList) || businessList.size() == 0)
        {
            throw new CustomException("导入业务类型数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ActDeBusiness actDeBusiness : businessList)
        {
            try
            {
                // 验证是否存在这条业务类型
                ActDeBusiness actDeBusinessNew = actDeBusinessMapper.selectActDeBusinessById(actDeBusiness.getId());
                if (StringUtils.isNull(actDeBusinessNew))
                {
                    this.insertActDeBusiness(actDeBusiness);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业务名称 " + actDeBusiness.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    this.updateActDeBusiness(actDeBusiness);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业务名称 " + actDeBusiness.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、业务名称 " + actDeBusiness.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、业务名称 " + actDeBusiness.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 新增业务类型和部门信息
     *
     * @param actDeBusiness 业务类型对象
     */
    public int insertActDept(ActDeBusiness actDeBusiness)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<ActDept> list = new ArrayList<ActDept>();
        for (String deptId : actDeBusiness.getDeptIds())
        {
        	ActDept rd = new ActDept();
            rd.setActId(actDeBusiness.getId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = actDeptMapper.batchActDept(list);
        }
        return rows;
    }

	@Override
	public List<String> selectDeptListByActId(String actId) {
		// TODO Auto-generated method stub
		return actDeptMapper.selectActDeptByActId(actId);
	}
	
	public String findDefinitionKeyByTableName(String tableName,String type) {
		Map<String,Object> para=new HashMap<String,Object>();
		para.put("tableName", tableName);
		para.put("type", type);
        List<ActDeBusiness> list= actDeBusinessMapper.findDefinitionKeyByTableName(para);

        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        if (list.size()==1) {
			return list.get(0).getDefId();
		}
        String userId=SecurityUtils.getUserId();
        for (ActDeBusiness activitiDeBusiness : list) {
        	int count=actDeptMapper.selectActDeptCount(userId,activitiDeBusiness.getId());
        	if (count>0) {
        		return activitiDeBusiness.getDefId();
			}
		}
        return list.get(0).getDefId();
    }

	@Override
	public String getChildDataType(String tableName, String dataId) {
		Map<String,Object> para=new HashMap<String,Object>();
		para.put("tableName", tableName);
		para.put("dataId", dataId);
		return actDeBusinessMapper.getChildDataType(para);
	}

	@Override
	public String findDefinitionId(String processDefinitionKey) {
		return actDeBusinessMapper.findDefinitionId(processDefinitionKey);
	}

	@Override
	public Boolean checkApproveByBizId(String bizId) {
		String userName=SecurityUtils.getUsername();
		Map<String,Object> para=new HashMap<String,Object>();
		para.put("userName", userName);
		para.put("bizId", bizId);
		return actDeBusinessMapper.checkApproveByBizId(para);
	}

	@Override
	public List<String> getNextApproveByBizId(String bizId) {
		String procInstId=actDeBusinessMapper.getProcInstIdByBizId(bizId);
		if (Objects.isNull(procInstId)) {
			return new ArrayList<String>();
		}
		return actDeBusinessMapper.getNextApproveByBizId(procInstId);
	}
	
	@Override
	public Map<String,List<String>> getNextApproveByBizId(List<String> bizIds) {
		Map<String,List<String>> map=new HashMap<String,List<String>>();
		for (String bizId : bizIds) {
			List<String> result=getNextApproveByBizId(bizId);
			map.put(bizId, result);
		}
		return map;
	}
}
